﻿using System;
using System.Web;
using System.Web.Security;
using BestEasyCMS.Framework.CookieStorage;
using BestEasyCMS.Service.Impl.Security.Users;
using BestEasyCMS.Web.MvcUI.Helper;
using StructureMap;

namespace BestEasyCMS.Web.MvcUI.Areas.BestEasyAdmin.Helper
{
    /// <summary>
    /// 帐户帮助类
    /// </summary>
    public class AccountHelper
    {
        private static readonly ICookieStorageService CookieStorageService = new CookieStorageService();
        private static CurrentAccount _currentAccount;


        public static CurrentAccount GetCurrentAccount()
        {
            if (_currentAccount != null)
                return _currentAccount;
            _currentAccount = new CurrentAccount();
            //获取用户ID
            var userId = CookieStorageService.GetCookieValue(CookieKeyHelper.UserCookieName,CookieKeyHelper.CurrentUId);
            if (userId == "")
            {
                FormsAuthentication.SignOut();
                return _currentAccount;
            }
            var userService = ObjectFactory.GetInstance<UserService>();
            var response = userService.FindBy(Convert.ToInt32(userId));
            if (!response.IsSuccess)
            {
                FormsAuthentication.SignOut();
                HttpContext.Current.Response.Redirect(FormsAuthentication.LoginUrl);
                return _currentAccount;
            }
            var user = response.View;

            _currentAccount.RoleId = user.RoleId;
            _currentAccount.UserId = user.Id;
            _currentAccount.LoginName = user.LoginName;
            return _currentAccount;
        }

        public static void SetAccount(CurrentAccount account)
        {
            _currentAccount = account;
        }

        public static void ClearCurrentAccount()
        {
            _currentAccount = null;
        }
    }

    public class CurrentAccount
    {
        public long UserId { get; set; }
        public long RoleId { get; set; }
        public string LoginName { get; set; }
        public string RoleName { get; set; }
    }
}